﻿using LeSoft.Application.Bussiness;
using LeSoft.Application.Cache;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;


namespace LeSoft.Application.Web.Areas.ResourceManage.Controllers
{
    public class RS_EnergyMeterController : MvcControllerBase
    {
        private EnergyBLL bll = new EnergyBLL();
        private PStructCache pstructCache = new PStructCache();
        private OrganizeCache organizeCache = new OrganizeCache();

        #region 视图
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Form()
        {
            return View();
        }
      

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult PublicForm()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        public ActionResult ReadingIndex()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult TypeIndex()
        {
            string ItemCode = Request["ItemCode"];
            var data = new DataItemBLL().GetEntityByCode(ItemCode);
            ViewBag.itemId = data.ItemId;
            ViewBag.isTree = data.IsTree;
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult TypeForm()
        {
            return View();
        }
        #endregion
        #region 资料
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        public ActionResult GetDataItemTreeJson(string EnCode)
        {
            var data = new DataItemCache().GetDataItemList(EnCode);
            var treeList = new List<TreeEntity>();
            TreeEntity tree1 = new TreeEntity { id = "All", text = "所有费表类别", value = "All", parentId = "0", isexpand = true, complete = true, hasChildren = true };
            treeList.Add(tree1);
            foreach (DataItemModel item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.ParentId == item.ItemDetailId) == 0 ? false : true;
                tree.id = item.ItemDetailId;
                tree.text = item.ItemName;
                tree.value = item.ItemValue;
                tree.parentId = item.ParentId == "0" ? "All" : item.ParentId;
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }

        [HttpGet]
        public ActionResult GetList(string queryJson)
        {
            var queryParam = queryJson.ToJObject();
            var data = bll.GetList().ToList();
            if (!queryParam["Nature"].IsEmpty())
            {
                data = data.Where(t => t.Nature == queryParam["Nature"].ToString()).ToList();
            }
            if (!queryParam["Type"].IsEmpty())
            {
                data = data.Where(t => t.Type == queryParam["Type"].ToString()).ToList();
            }
            if (!queryParam["condition"].IsEmpty() && !queryParam["keyword"].IsEmpty())
            {
                var condition = queryParam["condition"].ToString();
                var keyword = queryParam["keyword"].ToString();
                switch (condition)
                {
                    case "Name":
                        data = data.Where(t => t.Name.Contains(keyword)).ToList();
                        break;
                    default:
                        break;
                }
            }
            foreach (var a in data)
            {
                switch (a.Nature)
                {
                    case "1": a.Nature = "单元表"; break;
                    case "2": a.Nature = "公用表"; break;
                    case "3": a.Nature = "虚拟表"; break;
                    default: break;
                }
                var Type = new DataItemDetailBLL().GetEntity(a.Type);
                a.Type = Type != null ? Type.ItemName : "";
                //var feeitem = new FeeItemBLL().GetEntity("", a.EnergyFeeItem);
                //a.EnergyFeeItem = feeitem != null ? feeitem.Name : "";
            }
            return Content(data.ToJson());
        }

        [HttpGet]
        [HandlerAction(OperationType.GetForm,"费表资料","GetInfoFormJson")]
        public ActionResult GetInfoFormJson(string keyValue)
        {
            var data = bll.GetEntity(keyValue);        
            return Content(data.ToJson());
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create,"费表资料","SaveForm")]
        public ActionResult SaveForm(string keyValue, string EnergyMeter,string FeeItemListStr)
        {
            try
            {
                EnergyMeterInfoEntity entity = EnergyMeter.ToObject<EnergyMeterInfoEntity>();
                List<RelationEnergyFeeItemEntity> list = new List<RelationEnergyFeeItemEntity>();
                string[] FeeItemList = FeeItemListStr.Split(',');
                if (FeeItemList != null && FeeItemList.Count() > 0)
                {
                    foreach (var item in FeeItemList)
                    {
                        list.Add(new RelationEnergyFeeItemEntity { FeeItemId = item ,EnabledMark=1});
                    }
                }
                bll.SaveForm(keyValue, entity, list);
                return Success("操作成功。");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }

     
        [HttpGet]
        public ActionResult GetParentTreeJson(string id = "", string Nature = "")
        {
            var data = bll.GetInstanceList();
            if (!string.IsNullOrEmpty(id))
                data = data.Where(t => t.Id != id);
            if (!string.IsNullOrEmpty(Nature))
                data = data.Where(t => t.Nature == Nature);
            var treeList = new List<TreeEntity>();
            foreach (EnergyMeterInstanceEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                bool hasChildren = data.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.ParentId;
                tree.parentId = string.IsNullOrEmpty(item.ParentId) ? "0" : item.ParentId;
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = hasChildren;
                treeList.Add(tree);
            }
            return Content(treeList.ToJson());

        }

        public ActionResult RemoveForm(string keyValue)
        {
            try
            {
                bll.RemoveForm(keyValue);
                return Success("删除成功。");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }

        }
        #endregion
        #region 装表
      

        #region 验证数据
        /// <summary>
        /// 编号不能重复
        /// </summary>
        /// <param name="Code">编号</param>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ExistInstanceCode(string Code, string keyValue)
        {
            bool IsOk = bll.ExistInstanceCode(Code, keyValue);
            return Content(IsOk.ToString());
        }
        /// <summary>
        /// 名称不能重复
        /// </summary>
        /// <param name="Name">名称</param>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ExistInstanceName(string Name, string keyValue)
        {
            bool IsOk = bll.ExistInstanceName(Name, keyValue);
            return Content(IsOk.ToString());
        }
        #endregion

        public ActionResult GetReadingEnergyMeterList(string queryJson)
        {
            var queryParam = queryJson.ToJObject();
            var data = bll.GetInstanceList().ToList();
            if (!queryParam["PStructId"].IsEmpty())
            {
                var PStructId = queryParam["PStructId"].ToString();
                data = data.Where(t => PStructId.Contains(t.PStructId)).ToList();
            }
            if (!queryParam["Type"].IsEmpty())
            {
                data = data.Where(t => t.Type == queryParam["Type"].ToString()).ToList();
            }
            if (!queryParam["Nature"].IsEmpty())
            {
                var Nature = queryParam["Nature"].ToString();
                data = data.Where(t => Nature.Contains(t.Nature)).ToList();
            }
            if (!queryParam["ScaleDate"].IsEmpty())
            {
                var ScaleDate = queryParam["ScaleDate"].ToDate();
                DateTime ScaleDate1 = ScaleDate.AddDays(-1);
                DateTime ScaleDate2 = ScaleDate.AddDays(1);
                data = (from s in data where s.ScaleDate > ScaleDate1 && s.ScaleDate < ScaleDate2 select s).ToList();
            }

            foreach (var a in data)
            {
                a.PStructId = new PStructBLL().GetEntity(a.PStructId).AllName;
                switch (a.Nature)
                {
                    case "1": a.Nature = "单元表"; break;
                    case "2": a.Nature = "公用表"; break;
                    case "3": a.Nature = "虚拟表"; break;
                    default: break;
                }
                if (!a.ParentId.IsEmpty())
                {
                    var parent = bll.GetInstanceEntity(a.ParentId);
                    a.ParentId = parent == null ? "" : parent.Name + "/" + parent.Code + "/" + parent.PSMemo;
                }
                a.Type = new DataItemDetailBLL().GetEntity(a.Type).ItemName;
            }

            return Content(data.ToJson());
        }

        public ActionResult GetPublicFormJson(string keyValue)
        {
            var data = bll.GetInstanceEntity(keyValue);
            return Content(data.ToJson());
        }

        public ActionResult SaveInstanceForm(string keyValue, EnergyMeterInstanceEntity entity)
        {
            entity.UnitPrice = Convert.ToDecimal(entity.UnitPrice);
            try
            {
                bll.SaveInstanceForm(keyValue, entity);
                return Success("操作成功。");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }

     
        //public ActionResult GetUnitTree()
        //{
        //    var DataProperty = new PStructBLL().GetList().Where(t => t.EnabledMark == 1 && t.Type == 1).ToList();
        //    var EnergymeterInfo = bll.GetList().Where(t => t.EnabledMark == 1 && t.Nature == "1").ToList();//单元表
        //    var treeList = new List<TreeEntity>();
        //    foreach (PStructEntity item in DataProperty)
        //    {
        //        TreeEntity tree = new TreeEntity();
        //        bool hasChildren = DataProperty.Count(t => t.ParentId == item.Id) == 0 ? false : true;
        //        if (hasChildren == false)
        //        {
        //            hasChildren = EnergymeterInfo.Count(t => t.PStructId == item.Id) == 0 ? false : true;
        //        }
        //        tree.id = item.Id;
        //        tree.text = item.Name;
        //        tree.value = item.Id;
        //        tree.parentId = DataProperty.Count(t => t.Id == item.ParentId) == 0 ? "0" : item.ParentId;
        //        tree.isexpand = true;
        //        tree.complete = true;
        //        tree.Attribute = "Type";
        //        tree.AttributeValue = "0";
        //        tree.hasChildren = hasChildren;
        //        treeList.Add(tree);
        //    }
        //    foreach (EnergyMeterInfoEntity item in EnergymeterInfo)
        //    {
        //        TreeEntity tree = new TreeEntity();
        //        tree.id = item.Id;
        //        tree.text = item.Name;
        //        tree.value = item.Nature;
        //        tree.title = item.Type;
        //        tree.parentId = item.PStructId;
        //        tree.isexpand = true;
        //        tree.complete = true;
        //        tree.hasChildren = false;
        //        tree.Attribute = "Type";
        //        tree.AttributeValue = "1";
        //        treeList.Add(tree);
        //    }
        //    return Content(treeList.TreeToJson());
        //}

      

     
      
        #endregion

    

    }
}
